﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace txt_file_reader
{
    internal class NovelReader
    {
        private int cacheVoiceCount = 10; //后台缓存多少数据
        private Dictionary<int, Line> voiceDictionary = new Dictionary<int, Line>();
        private int cachedLineIndex = 0;
        private int readingIndex = 0;//正在读的文本索引
        public NovelReader(int cacheVoiceCount)
        {
            this.cacheVoiceCount = cacheVoiceCount;
            this.readingIndex = 0;
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        void cacheText(string[] lines, int index)
        {
            if (!voiceDictionary.ContainsKey(index))
            {
                Line line = new Line();
                this.voiceDictionary[index] = line;
                string text = lines[index];
                line.setText(lines[index],index);
            }
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public Line getLine(int index) 
        {
            Line line = voiceDictionary[index];
            return line;
        }
        void removeUnused(int cacheStart,int cacheEnd)
        {
            foreach (int key in this.voiceDictionary.Keys)
            {
                if(key > cacheEnd || key < cacheStart)
                {
                    Line line = voiceDictionary[key];
                    line.destory();
                    this.voiceDictionary.Remove(key);
                }
            }

        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        public void read(string[] lines, int index)
        {
            this.readingIndex = index;
            this.cacheLinesFrom(lines,index);
        }
        //重置缓存
        [MethodImpl(MethodImplOptions.Synchronized)]
        private void cacheLinesFrom(String[] lines,int index)
        {
            for(int i = index;i < index + this.cacheVoiceCount;i++)
            {
                if (i < lines.Length)
                {
                    this.cacheText(lines, i);
                }
            }
            //删除不需要缓存的内容
            this.removeUnused(index, index + this.cacheVoiceCount-1);
        }
        public void play(int index)
        {
            Line line = this.getLine(index);
            if(line == null)
            {
                return;
            }
            line.playThenDestory();

        }

        internal void stop()
        {
            Line line = this.getLine(this.readingIndex);
            if (line == null)
            {
                return;
            }
            line.stop();
        }
    }
}
